define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'order/index' + location.search,
                    add_url: 'order/add',
                    edit_url: 'order/edit',
                    del_url: 'order/del',
                    multi_url: 'order/multi',
                    import_url: 'order/import',
                    table: 'order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder: 'desc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: 'ID', width: 60},
                        {field: 'order_no', title: '订单号', operate: 'LIKE', width: 140},
                        {field: 'merchant_name', title: '商家名称', operate: 'LIKE', width: 100},
                        {field: 'order_type', title: '订单类型', width: 80, formatter: function(value, row, index) {
                            // 根据attribute_type值判断订单类型
                            if (row.attribute_type) {
                                switch(parseInt(row.attribute_type)) {
                                    case 1:
                                        return '权益商品';
                                    case 2:
                                        return '积分商品';
                                    case 3:
                                        return '助农商品';
                                    default:
                                        return '普通订单';
                                }
                            }
                            return value || '普通订单';
                        }},
                        {field: 'product_info', title: '商品信息', operate: false, width: 280, formatter: function(value, row, index) {
                            // 处理后端返回的product_info数组数据
                            if (value && Array.isArray(value) && value.length > 0) {
                                var html = '';
                                
                                // 遍历商品信息数组，显示每个商品
                                for (var i = 0; i < value.length; i++) {
                                    var product = value[i];
                                    
                                    html += '<div style="display: flex; align-items: center; padding: 5px; ' + (i > 0 ? 'border-top: 1px solid #eee; margin-top: 5px; padding-top: 8px;' : '') + '">';
                                    
                                    // 商品图片
                                    if (product.image) {
                                        html += '<div style="margin-right: 10px; flex-shrink: 0;">';
                                        html += '<img src="' + product.image + '" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd;" onerror="this.src=\'/assets/img/default-product.png\'">';
                                        html += '</div>';
                                    } else {
                                        // 默认图片占位
                                        html += '<div style="margin-right: 10px; flex-shrink: 0;">';
                                        html += '<div style="width: 50px; height: 50px; background-color: #f5f5f5; border: 1px solid #ddd; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #999; font-size: 12px;">暂无图片</div>';
                                        html += '</div>';
                                    }
                                    
                                    // 商品信息
                                    html += '<div style="flex: 1; min-width: 0;">';
                                    
                                    // 商品名称
                                    if (product.name) {
                                        html += '<div style="font-weight: bold; color: #333; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + product.name + '">';
                                        html += product.name;
                                        html += '</div>';
                                    }
                                    
                                    // 商品ID
                                    if (product.id) {
                                        html += '<div style="color: #666; font-size: 12px; margin-bottom: 2px;">';
                                        html += 'ID: ' + product.id;
                                        html += '</div>';
                                    }
                                    
                                    // 商品规格/SKU信息 - 优先使用product对象中的sku_name
                                    var skuName = '';
                                    if (product.sku_name) {
                                        skuName = product.sku_name;
                                    } else if (row.product_sku && row.product_sku.sku_name) {
                                        skuName = row.product_sku.sku_name;
                                    }
                                    
                                    if (skuName) {
                                        html += '<div style="color: #999; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="' + skuName + '">';
                                        html += skuName;
                                        html += '</div>';
                                    }
                                    
                                    html += '</div>';
                                    html += '</div>';
                                }
                                
                                return html;
                            }
                            
                            // 如果没有详细商品信息，显示默认值
                            return '<div style="text-align: center; color: #999; padding: 10px;">暂无商品信息</div>';
                        }},
                        {field: 'avg_price', title: '单价', operate:'RANGE', addclass:'text-center', sortable: true, width: 80, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'total_quantity', title: '数量', operate:'RANGE', addclass:'text-center', sortable: true, width: 60},
                        {field: 'merchant_income', title: '商家收益金额', operate:'RANGE', addclass:'text-center', sortable: true, width: 100, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'pay_amount', title: '实收金额', operate:'RANGE', addclass:'text-center', sortable: true, width: 80, formatter: function(value, row, index) {
                            return '¥' + parseFloat(value || 0).toFixed(2);
                        }},
                        {field: 'buyer_info', title: '买家/收货人', operate: false, width: 120, formatter: function(value, row, index) {
                            return value || '-';
                        }},
                        {field: 'receiver_address', title: '收货地址', operate: false, width: 200, formatter: function(value, row, index) {
                            // 在前端组合地址信息
                            var address = '';
                            if (row.province) address += row.province;
                            if (row.city) address += row.city;
                            if (row.district) address += row.district;
                            if (row.address) address += row.address;
                            return address || '-';
                        }},
                        {field: 'pay_type', title: '支付方式', searchList: {"0":"未支付","1":"微信支付","2":"支付宝支付","3":"余额支付","4":"权益积分支付","5":"绿色积分支付"}, formatter: Table.api.formatter.normal, width: 80},
                        {field: 'order_status', title: '订单状态', searchList: {"0":"待付款","1":"已付款","2":"已发货","3":"已完成","4":"已取消","5":"已退款"}, formatter: Table.api.formatter.normal, width: 80},
                        {field: 'operate', title: '操作', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, width: 120,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: __('Detail'),
                                    title: __('Detail'),
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'order/detail',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        return true;
                                    }
                                },
                                {
                                    name: 'ship',
                                    text: '发货',
                                    title: '发货',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    icon: 'fa fa-truck',
                                    url: 'order/ship',
                                    visible: function (row) {
                                        return row.order_status == 1; // 只有已付款的订单才显示发货按钮
                                    }
                                },
                                {
                                    name: 'print',
                                    text: '打印',
                                    title: '打印',
                                    classname: 'btn btn-xs btn-success',
                                    icon: 'fa fa-print',
                                    url: 'order/print',
                                    extend: 'data-area=\'["100%","100%"]\'',
                                    visible: function (row) {
                                        return true;
                                    },
                                    click: function (event, value, row, index) {
                                        var url = Backend.api.fixurl('order/print/ids/' + row.id);
                                        Fast.api.open(url, '打印订单', {
                                            area: ['90%', '90%'],
                                            type: 2
                                        });
                                        return false;
                                    }
                                }
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 绑定TAB事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.size() > 0) {
                    Controller.index();
                    return;
                }
                var field = $(this).closest("ul").data("field");
                var value = $(this).data("value");
                var filter = {};
                if (value !== '') {
                    filter[field] = value;
                }
                table.bootstrapTable('refresh', {query: filter});
                return false;
            });

            // 批量发货
            $(document).on('click', '.btn-batchship', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.error(__('Please select at least one record'));
                    return false;
                }
                Fast.api.open('order/batchship', '批量发货', {
                    area: ['500px', '300px'],
                    callback: function(value) {
                        var data = value;
                        data.ids = ids.join(',');
                        Fast.api.ajax({
                            url: 'order/batchship',
                            data: data,
                        }, function(data, ret) {
                            table.bootstrapTable('refresh');
                        });
                    }
                });
            });

            // 批量打印
            $(document).on('click', '.btn-batchprint', function () {
                var ids = Table.api.selectedids(table);
                if (ids.length === 0) {
                    Toastr.error(__('Please select at least one record'));
                    return false;
                }
                var url = Backend.api.fixurl('order/batchprint/ids/' + ids.join(','));
                Fast.api.open(url, '批量打印订单', {
                    area: ['90%', '90%'],
                    type: 2
                });
            });

            // 导出订单
            $(document).on('click', '.btn-export', function () {
                var options = table.bootstrapTable('getOptions');
                var url = Backend.api.fixurl('order/export');
                var params = {};
                if (options.queryParams) {
                    params = options.queryParams({});
                }
                Fast.api.ajax({
                    url: url,
                    data: params,
                    type: 'GET'
                }, function(data, ret) {
                    // 创建下载链接
                    var link = document.createElement('a');
                    link.href = url + '?' + $.param(params);
                    link.download = '订单列表_' + new Date().getTime() + '.csv';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }, function() {
                    // 如果ajax失败，直接跳转下载
                    window.location.href = url + '?' + $.param(params);
                });
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            Controller.api.bindevent();
        },
        ship: function () {
            Controller.api.bindevent();
        },
        print: function () {
            // 打印页面不需要绑定事件
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});